package com.example.pclimb.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.pclimb.databinding.FragmentHomeBinding;
import com.example.pclimb.model.User;
import com.example.pclimb.ui.guides.GuideDetailActivity;
import com.example.pclimb.ui.requests.AvailableRequestsActivity;
import com.example.pclimb.ui.requests.CreateRequestActivity;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.TravelGuideViewModel;
import com.example.pclimb.viewmodel.UserViewModel;

public class HomeFragment extends Fragment {

    private static final String TAG = "HomeFragment";
    private FragmentHomeBinding binding;
    private TravelGuideViewModel travelGuideViewModel;
    private UserViewModel userViewModel;
    private PopularGuidesAdapter adapter;
    private Button btnTakeRequests;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: HomeFragment创建");
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: HomeFragment视图创建");
        
        try {
            // 初始化ViewModel
            travelGuideViewModel = new ViewModelProvider(this).get(TravelGuideViewModel.class);
            userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
            
            // 初始化接取申请按钮
            btnTakeRequests = binding.btnTakeRequests;
            
            // 设置RecyclerView
            adapter = new PopularGuidesAdapter();
            binding.recyclerPopularGuides.setLayoutManager(new LinearLayoutManager(requireContext()));
            binding.recyclerPopularGuides.setAdapter(adapter);
            
            // 设置攻略点击事件
            adapter.setOnItemClickListener(travelGuide -> {
                // 跳转到攻略详情页面
                Intent intent = new Intent(requireActivity(), GuideDetailActivity.class);
                intent.putExtra("guide_id", travelGuide.getId());
                startActivity(intent);
            });
            
            // 加载热门攻略数据
            travelGuideViewModel.getTopViewedGuides().observe(getViewLifecycleOwner(), travelGuides -> {
                if (travelGuides != null) {
                    Log.d(TAG, "观察到旅游攻略数据: " + travelGuides.size() + "条");
                    adapter.setTravelGuides(travelGuides);
                }
            });
            
            // 创建陪爬申请按钮点击事件
            binding.btnCreateRequest.setOnClickListener(v -> {
                Log.d(TAG, "点击创建陪爬申请按钮");
                // 跳转到创建陪爬申请界面
                Intent intent = new Intent(requireActivity(), CreateRequestActivity.class);
                startActivity(intent);
            });
            
            // 接取申请按钮点击事件
            btnTakeRequests.setOnClickListener(v -> {
                Log.d(TAG, "点击接取申请按钮");
                // 跳转到接取申请界面
                Intent intent = new Intent(requireActivity(), AvailableRequestsActivity.class);
                startActivity(intent);
            });
            
            // 检查用户类型，决定是否显示接取申请按钮
            checkUserType();
        } catch (Exception e) {
            Log.e(TAG, "初始化HomeFragment时出错: ", e);
        }
    }
    
    /**
     * 检查用户类型，决定是否显示接取申请按钮
     */
    private void checkUserType() {
        int userId = SharedPreferencesUtil.getUserId(requireContext());
        if (userId > 0) {
            userViewModel.getUserById(userId).observe(getViewLifecycleOwner(), user -> {
                if (user != null) {
                    // 如果是陪爬人员，显示接取申请按钮
                    if (user.isGuide() || user.getUserType() == User.TYPE_GUIDE) {
                        btnTakeRequests.setVisibility(View.VISIBLE);
                    } else {
                        btnTakeRequests.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 恢复时刷新热门攻略数据
        refreshTopGuides();
        // 检查用户类型
        checkUserType();
    }
    
    /**
     * 刷新热门攻略数据
     */
    private void refreshTopGuides() {
        if (travelGuideViewModel != null) {
            travelGuideViewModel.refreshTopViewedGuides();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
} 